import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useUserStore = defineStore('user', () => {
    const user = ref(null)
    const token = ref(localStorage.getItem('token') || null)

    function setUser(userData) {
        user.value = userData
    }

    function setToken(newToken) {
        token.value = newToken
        localStorage.setItem('token', newToken)
    }

    function updateAvatar(avatarUrl) {
        if (user.value) {
            user.value = {
                ...user.value,
                avatar: avatarUrl
            }
        }
    }

    function updateUserInfo(userInfo) {
        if (user.value) {
            user.value = {
                ...user.value,
                ...userInfo
            }
        }
    }

    function logout() {
        user.value = null
        token.value = null
        localStorage.removeItem('token')
    }

    const isAuthenticated = computed(() => !!token.value)

    return {
        user,
        token,
        setUser,
        setToken,
        updateAvatar,
        updateUserInfo,
        logout,
        isAuthenticated
    }
})